/**
 * 高德地图服务类
 * 处理定位、地点搜索、导航等功能
 */

// 高德地图配置
const AMAP_CONFIG = {
  key: '341dbca57f8782a04a2e9ed52d2f600d',  // 您的高德Key
  webServiceHost: 'https://restapi.amap.com'  // WebAPI服务地址
};

// 安全密钥配置（小程序端请使用secure服务处理，这里仅为示例）
if (typeof window !== 'undefined') {
  window._AMapSecurityConfig = {
    securityJsCode: '您需要添加您的安全密钥',
  };
}

/**
 * 获取当前位置
 * @param {Object} options 配置选项
 * @returns {Promise} Promise对象
 */
export function getCurrentLocation(options = {}) {
  const defaultOptions = {
    type: '1', // 获取方式，1:获取一次；0:持续获取
    timeout: 3000 // 超时时间
  };
  
  const mergedOptions = {...defaultOptions, ...options};
  
  return new Promise((resolve, reject) => {
    // 检查权限
    uni.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] !== false) {
          // 获取位置
          uni.getLocation({
            type: 'gcj02',
            success: (location) => {
              console.log('原生定位成功:', location);
              resolve(location);
            },
            fail: (err) => {
              console.error('原生定位失败:', err);
              reject(err);
            }
          });
        } else {
          // 引导用户授权
          uni.showModal({
            title: '需要位置权限',
            content: '请允许使用您的位置信息以便提供定位和导航服务',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting({
                  success: (res) => {
                    if (res.authSetting['scope.userLocation']) {
                      // 用户允许授权，重新获取位置
                      uni.getLocation({
                        type: 'gcj02',
                        success: (location) => {
                          resolve(location);
                        },
                        fail: (err) => {
                          reject(err);
                        }
                      });
                    } else {
                      reject(new Error('用户拒绝位置授权'));
                    }
                  }
                });
              } else {
                reject(new Error('用户取消授权'));
              }
            }
          });
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 搜索周边兴趣点
 * @param {Object} options 搜索选项
 * @param {String} options.keywords 关键词
 * @param {Number} options.latitude 中心点纬度
 * @param {Number} options.longitude 中心点经度
 * @param {Number} options.radius 搜索半径，单位米，默认1000
 * @returns {Promise} Promise对象
 */
export function searchNearby(options) {
  if (!options.keywords) {
    return Promise.reject(new Error('关键词不能为空'));
  }
  
  if (!options.latitude || !options.longitude) {
    return Promise.reject(new Error('中心点坐标不能为空'));
  }
  
  const defaultOptions = {
    radius: 1000,
    offset: 20,  // 每页记录数
    page: 1      // 页码
  };
  
  const mergedOptions = {...defaultOptions, ...options};
  
  // 构建API请求URL
  const url = `${AMAP_CONFIG.webServiceHost}/v3/place/around`;
  
  // 构建请求参数
  const requestData = {
    key: AMAP_CONFIG.key,
    keywords: mergedOptions.keywords,
    location: `${mergedOptions.longitude},${mergedOptions.latitude}`,
    radius: mergedOptions.radius,
    offset: mergedOptions.offset,
    page: mergedOptions.page,
    extensions: 'all'
  };
  
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      data: requestData,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.status === '1') {
          // 处理返回数据，转换为标准格式
          const pois = (res.data.pois || []).map((poi, index) => {
            return {
              id: poi.id || `poi_${index}`,
              name: poi.name,
              address: poi.address,
              latitude: parseFloat(poi.location.split(',')[1]),
              longitude: parseFloat(poi.location.split(',')[0]),
              distance: poi.distance,
              type: poi.type,
              tel: poi.tel,
              photos: poi.photos,
              businessHours: poi.business_hours
            };
          });
          
          resolve({
            pois: pois,
            count: res.data.count
          });
        } else {
          reject(new Error(res.data.info || '搜索失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 路线规划
 * @param {Object} options 路线规划选项
 * @param {Object} options.origin 起点，格式 {latitude, longitude}
 * @param {Object} options.destination 终点，格式 {latitude, longitude}
 * @param {String} options.mode 出行方式，可选值：driving（驾车）、walking（步行）、bicycling（骑行）、transit（公交）,默认driving
 * @returns {Promise} Promise对象
 */
export function calculateRoute(options) {
  if (!options.origin || !options.destination) {
    return Promise.reject(new Error('起点和终点不能为空'));
  }
  
  const defaultOptions = {
    mode: 'walking'  // 默认步行
  };
  
  const mergedOptions = {...defaultOptions, ...options};
  
  // 根据出行方式选择API
  let apiPath = '';
  switch (mergedOptions.mode) {
    case 'driving':
      apiPath = 'v3/direction/driving';
      break;
    case 'walking':
      apiPath = 'v3/direction/walking';
      break;
    case 'bicycling':
      apiPath = 'v3/direction/bicycling';
      break;
    case 'transit':
      apiPath = 'v3/direction/transit/integrated';
      break;
    default:
      apiPath = 'v3/direction/walking';
  }
  
  // 构建API请求URL
  const url = `${AMAP_CONFIG.webServiceHost}/${apiPath}`;
  
  // 构建请求参数
  const requestData = {
    key: AMAP_CONFIG.key,
    origin: `${options.origin.longitude},${options.origin.latitude}`,
    destination: `${options.destination.longitude},${options.destination.latitude}`,
    output: 'json',
    extensions: 'all'
  };
  
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      data: requestData,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.status === '1') {
          // 处理不同出行方式的返回结果
          let route = {};
          
          // 提取路线信息
          if (mergedOptions.mode === 'driving') {
            const routeData = res.data.route;
            const path = routeData.paths[0];
            
            route = {
              distance: path.distance,  // 路线距离，单位：米
              duration: path.duration,  // 预计用时，单位：秒
              polyline: processPolyline(path.steps),
              steps: path.steps.map(step => ({
                instruction: step.instruction,
                distance: step.distance,
                duration: step.duration,
                polyline: step.polyline
              })),
              taxi_cost: routeData.taxi_cost // 打车费用，单位：元
            };
          } else if (mergedOptions.mode === 'walking' || mergedOptions.mode === 'bicycling') {
            const path = res.data.route.paths[0];
            
            route = {
              distance: path.distance,
              duration: path.duration,
              polyline: processPolyline(path.steps),
              steps: path.steps.map(step => ({
                instruction: step.instruction,
                distance: step.distance,
                duration: step.duration,
                polyline: step.polyline
              }))
            };
          } else if (mergedOptions.mode === 'transit') {
            const routeData = res.data.route;
            
            route = {
              distance: routeData.distance,
              duration: routeData.duration,
              routes: routeData.transits.map(transit => ({
                cost: transit.cost,
                duration: transit.duration,
                distance: transit.distance,
                segments: transit.segments.map(segment => ({
                  type: segment.type,
                  instruction: segment.instruction,
                  polyline: segment.polyline
                }))
              }))
            };
          }
          
          resolve(route);
        } else {
          reject(new Error(res.data.info || '路线规划失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 处理polyline数据，转换为小程序地图组件需要的格式
 * @param {Array} steps 路径步骤
 * @returns {Array} 处理后的路径点数组
 */
function processPolyline(steps) {
  const points = [];
  
  steps.forEach(step => {
    if (step.polyline) {
      const polylinePoints = step.polyline.split(';');
      
      polylinePoints.forEach(point => {
        const [longitude, latitude] = point.split(',');
        points.push({
          longitude: parseFloat(longitude),
          latitude: parseFloat(latitude)
        });
      });
    }
  });
  
  return points;
}

/**
 * 地址解析（正向地理编码）
 * @param {String} address 地址
 * @returns {Promise} Promise对象
 */
export function geocode(address) {
  if (!address) {
    return Promise.reject(new Error('地址不能为空'));
  }
  
  // 构建API请求URL
  const url = `${AMAP_CONFIG.webServiceHost}/v3/geocode/geo`;
  
  // 构建请求参数
  const requestData = {
    key: AMAP_CONFIG.key,
    address: address,
    output: 'json'
  };
  
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      data: requestData,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.status === '1' && res.data.geocodes && res.data.geocodes.length > 0) {
          const geocode = res.data.geocodes[0];
          const [longitude, latitude] = geocode.location.split(',');
          
          resolve({
            address: geocode.formatted_address,
            latitude: parseFloat(latitude),
            longitude: parseFloat(longitude),
            adcode: geocode.adcode,
            province: geocode.province,
            city: geocode.city,
            district: geocode.district
          });
        } else {
          reject(new Error(res.data.info || '地址解析失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 逆地址解析（坐标转地址）
 * @param {Object} location 位置对象，格式 {latitude, longitude}
 * @returns {Promise} Promise对象
 */
export function reverseGeocode(location) {
  if (!location || !location.latitude || !location.longitude) {
    return Promise.reject(new Error('坐标不能为空'));
  }
  
  // 构建API请求URL
  const url = `${AMAP_CONFIG.webServiceHost}/v3/geocode/regeo`;
  
  // 构建请求参数
  const requestData = {
    key: AMAP_CONFIG.key,
    location: `${location.longitude},${location.latitude}`,
    extensions: 'all',
    output: 'json'
  };
  
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      data: requestData,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.status === '1' && res.data.regeocode) {
          const regeocode = res.data.regeocode;
          
          resolve({
            address: regeocode.formatted_address,
            addressComponent: regeocode.addressComponent,
            pois: (regeocode.pois || []).map((poi, index) => {
              return {
                id: poi.id || `poi_${index}`,
                name: poi.name,
                type: poi.type,
                distance: poi.distance,
                address: poi.address,
                location: poi.location,
                latitude: parseFloat(poi.location.split(',')[1]),
                longitude: parseFloat(poi.location.split(',')[0])
              };
            })
          });
        } else {
          reject(new Error(res.data.info || '逆地址解析失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 打开微信内置地图导航
 * @param {Object} options 导航选项
 * @param {String} options.name 目的地名称
 * @param {Number} options.latitude 目的地纬度
 * @param {Number} options.longitude 目的地经度
 * @param {String} options.address 目的地地址
 * @returns {Promise} Promise对象
 */
export function openMapApp(options) {
  if (!options.latitude || !options.longitude) {
    return Promise.reject(new Error('目的地坐标不能为空'));
  }
  
  return new Promise((resolve, reject) => {
    uni.openLocation({
      latitude: options.latitude,
      longitude: options.longitude,
      name: options.name || '目的地',
      address: options.address || '',
      scale: 18,
      success: () => {
        resolve();
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
} 